package com.basic.library.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.fragment.app.DialogFragment;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.basic.library.R;
import com.basic.library.utils.MapUtil;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * 选择地图
 *
 * @author yys
 */
public class GuideDialogFragment extends DialogFragment implements OnClickListener {

    private Intent intent;
    private String endAdrs, lat, lng;
    private Activity context;


    public static GuideDialogFragment getInstance(String lat, String lng, String endAdrs) {
        GuideDialogFragment newFragment = new GuideDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putString("lat", lat);
        bundle.putString("lng", lng);
        bundle.putString("endAdrs", endAdrs);
        newFragment.setArguments(bundle);
        return newFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            lat = args.getString("lat");
            lng = args.getString("lng");
            endAdrs = args.getString("endAdrs");
            if (lat == null) {
                try {
                    geo();
                } catch (Exception e) {
                }
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().getWindow().requestFeature(STYLE_NO_TITLE);
        View view = inflater.inflate(R.layout.base_fragment_choose_guide, container);
        view.findViewById(R.id.tv_baidu).setOnClickListener(this);
        view.findViewById(R.id.tv_gaode).setOnClickListener(this);
        view.findViewById(R.id.tv_tencent).setOnClickListener(this);
        context = getActivity();
        return view;
    }

    void geo() throws AMapException {
        GeocodeSearch geocoderSearch = new GeocodeSearch(getActivity());
        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {

            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
                if (i == 1000) {
                    LatLonPoint latLonPoint = geocodeResult.getGeocodeAddressList().get(0).getLatLonPoint();
                    lat = String.valueOf(latLonPoint.getLatitude());
                    lng = String.valueOf(latLonPoint.getLongitude());
                }
            }
        });
        GeocodeQuery query = new GeocodeQuery(endAdrs, null);
        geocoderSearch.getFromLocationNameAsyn(query);
    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.tv_baidu) {
            double[] desLatLng = MapUtil.gaoDeToBaidu(Double.parseDouble(lat), Double.parseDouble(lng));
            lat = String.valueOf(desLatLng[0]);
            lng = String.valueOf(desLatLng[1]);
            gotoBaiduGuide();

        } else if (i == R.id.tv_gaode) {
            gotoAMapGuide();
        } else if (i == R.id.tv_tencent) {
            gotoTencentGuide();
        }
        GuideDialogFragment.this.dismiss();
    }

    private void gotoAMapGuide() {
        if (isAvilible(context, "com.autonavi.minimap")) {
            try {
                Intent intent = new Intent("android.intent.action.VIEW", Uri.parse("androidamap://navi?sourceApplication=数字工场&lat=" + lat + "&lon=" + lng + "&dev=0"));
                intent.setPackage("com.autonavi.minimap");
                context.startActivity(intent);
            } catch (Exception e) {
                gotoWebGuide(0);
            }
        } else {
            gotoWebGuide(0);
        }
    }

    @SuppressWarnings("deprecation")
    private void gotoBaiduGuide() {
        if (isAvilible(context, "com.baidu.BaiduMap")) {
            try {
                intent = Intent.getIntent("intent://map/direction?" +
                        //"origin=latlng:"+"34.264642646862,108.95108518068&" +   //起点  此处不传值默认选择当前位置
                        "destination=latlng:" + lat + "," + lng + "|name:我的目的地" +        //终点
                        "&mode=driving&" +          //导航路线方式
//                     "region=北京" +           //
                        "&src=" + endAdrs + "#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                context.startActivity(intent); //启动调用
            } catch (URISyntaxException e) {
                Log.e("intent", e.getMessage());
                gotoWebGuide(1);
            }
        } else {
            gotoWebGuide(1);
        }
    }

//    public static void openBrowserMap() {
//        Intent intent = new Intent();
//        intent.setAction("android.intent.action.VIEW");
//        intent.setData(Uri.parse("http://uri.amap.com/navigation?" +
//                "from=" + myLatLng.longitude + "," + myLatLng.latitude + "," + myAddress +
//                "to=" + lng + "," + lat + "," + endAdrs +
//                "&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=0"));
//        context.startActivity(intent);
//
//    }

    @SuppressWarnings("deprecation")
    private void gotoTencentGuide() {
        if (isAvilible(context, "com.tencent.map")) {
            try {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                intent.setData(Uri.parse("qqmap://map/routeplan?" +
                        "type=drive" +
                        "&from=" +
                        "&fromcoord=" +
                        "&to=" + endAdrs +
                        "&tocoord=" + lat + "," + lng +
                        "&policy=0" +
                        "&referer=appName"));
                context.startActivity(intent);
            } catch (Exception e) {
                Log.e("intent", e.getMessage());
                gotoWebGuide(2);
            }
        } else {
            gotoWebGuide(2);
        }
    }

    private void gotoWebGuide(int type) {
        if (type == 0) {
            Toast.makeText(context, "您尚未安装高德地图", Toast.LENGTH_LONG).show();
            Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(intent);
        } else if (type == 1) {
            Toast.makeText(context, "您尚未安装百度地图", Toast.LENGTH_LONG).show();
            Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(intent);
        } else if (type == 2) {
            Toast.makeText(context, "您尚未安装腾讯地图", Toast.LENGTH_LONG).show();
            Uri uri = Uri.parse("market://details?id=com.tencent.map");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(intent);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    public static boolean isAvilible(Context context, String packageName) {
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

}
